//本js库依赖于jquery
var Area = { area: {} };

//初始化地区
Area.Init = function() {
  var self = this;
  if (!self.area.province) {
    $.getJSON('area.json', function(data) {
      self.area = data.area;
      self.TranToArray();
    });
  }
};

//只有一个市或一个区的区域转成数组
Area.TranToArray = function() {
  $.each(Area.area.province, function(index, pro) {
    pro.city = Area.GetCity(pro);
    $.each(pro.city, function(index, city) {
      city.county = Area.GetCounty(city);
    });
  });
};

/**
 * [GetProvince 按照查询条件查找省份,返回省份数组]
 * @param {[String]} param [查询字符串，可选参数]
 */
Area.GetProvince = function(param) {
  return Area.Query(Area.area.province, param);
};

/**
 * [GetCity 按照查询条件查找指定省份的城市]
 * @param {[Object]} province [省份，必须]
 * @param {[String]} param [查询字符串，可选参数]
 */
Area.GetCity = function(province, param) {
  if (!province) {
    return [];
  }
  return Area.Query(province.city, param);
};

/**
 * [GetCounty 按照查询条件查找指定城市的区县]
 * @param {[Object]} city  [城市，必须]
 * @param {[String]} param [查询字符串，可选参数]
 */
Area.GetCounty = function(city, param) {
  if (!city) {
    return [];
  }
  return Area.Query(city.county, param);
};

/**
 * [isMatch 区域对象是否符合查询条件]
 * @param  {[Object]}  area  [区域对象（省/市/区）]
 * @param  {[String]}  param [查询字符串，可选参数]
 * @return {Boolean}       [是否符合]
 */
Area.Match = function(area, param) {
  param = $.trim(param).toLowerCase();
  if (param) {
    //匹配到名称或行政区划码
    var result = area.name.indexOf(param) >= 0 || area.code.indexOf(param) >= 0;

      //当引入了pinyinUtil.js才匹配拼音
    if (!result && (typeof pinyinUtil != 'undefined')) {
      //匹配名称的全拼
      var fullpy = pinyinUtil.getPinyin(area.name, '', 0, 1) || '';
      if (fullpy.length > 0) {
        for (var i = 0; i < fullpy.length; i++) {
          result = fullpy[i].toLowerCase().indexOf(param) == 0;
          if (result) break;
        }
      }
    }

    if (!result && (typeof pinyinUtil != 'undefined')) {
      //匹配名称的简拼
      var abbpy = pinyinUtil.getFirstLetter(area.name, 1) || '';
      if (abbpy.length > 0) {
        for (var i = 0; i < abbpy.length; i++) {
          result = abbpy[i].toLowerCase().indexOf(param) == 0;
          if (result) break;
        }
      }
    }
    return result;
  }
  return true;
};

/**
 * [Query description]
 * @param {[type]} area  [区域数组/对象(省/市/区)]
 * @param {[type]} param [description]
 * @return {Object}       [是否符合]
 */
Area.Query = function(area, param) {
  var _area = [];
  if ($.isArray(area)) {
    $.each(area, function(index, subArea) {
      if (Area.Match(subArea, param)) {
        _area.push(subArea);
      }
    });
  } else if (area) {
    if (Area.Match(area, param)) {
      _area.push(area);
    }
  }

  return _area;
};

/**
 * [BindSelect 绑定Select控件组]
 * @param {[Object]} option [需绑定的控件组{province:省份控件,city:城市控件,county:区/县控件}]
 * @param {[Object]} currVar [需赋值的当前选中对象 {currProvince:当前选中省份,currCity:当前选中城市,currCounty:当前选中区/县}]
 */
Area.BindSelect = function(option, currVar) {
  if (!option) {
    throw "请指定绑定控件！{province:省份控件,city:城市控件,county:区/县控件}";
  }
  var self = this;
  self.Init();
  //var currProvince, currCity, currCounty;
  currVar = currVar || {};
  var proSlt = $(option.province);
  var citySlt = $(option.city);
  var countySlt = $(option.county);

  countySlt.on("change", "", function() {
    currVar.currCounty = currVar.currCity ? currVar.currCity.county[$(this).find("option:selected").attr('index')] : {};
  });

  citySlt.on("change", "", function() {
    currVar.currCity = currVar.currProvince ? currVar.currProvince.city[$(this).find("option:selected").attr('index')] : {};
    if (countySlt) {
      //console.log(countySlt);
      setSltSource(countySlt, Area.GetCounty(currVar.currCity));
    }
  });

  proSlt.on("change", "", function() {
    currVar.currProvince = self.area.province[$(this).find("option:selected").attr('index')];
    if (citySlt) {
      //console.log(citySlt);
      setSltSource(citySlt, Area.GetCity(currVar.currProvince));
    }
  });

  function setSltSource(slt, area) {
    slt.html('');
    //slt.append('<option value="">请选择</option>');
    $.each(area, function(index, _area) {
      slt.append('<option index=' + index + ' code=' + _area.code + ' value="' + _area.name + '">' + _area.name + '</option>');
    });
    slt.change();
  };

  setTimeout(function() {
    setSltSource(proSlt, self.area.province);
  }, 300);
};
